package com.qws.xprinter.flutter_xprinter

import android.app.Application
import android.content.Context
import android.hardware.usb.UsbManager
import android.os.Build
import androidx.annotation.RequiresApi
import com.qws.xprinter.flutter_xprinter.bean.UsbInfo
import io.flutter.plugin.common.MethodChannel
import net.posprinter.POSConnect

/**
 * @author: star
 * @date: 2022-04-26
 */
class App : Application() {
    var channel: MethodChannel? = null

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate() {
        super.onCreate()
        app = this
        POSConnect.init(this)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun getUsbDevices(): ArrayList<UsbInfo> {
        val usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        val map = usbManager.deviceList
        val devices = arrayListOf<UsbInfo>()
        map.forEach { (s, usbDevice) ->
            usbDevice?.let {
                val mode = if (it.manufacturerName == null) {
                    "未知设备"
                } else {
                    it.manufacturerName
                }
                for (index in 0 until it.interfaceCount) {
                    if (it.getInterface(index).interfaceClass == 7 && it.getInterface(index).interfaceSubclass == 1) {
                        devices.add(UsbInfo(mode!!, usbDevice.deviceName))
                        break
                    }
                }
            }
        }
        return devices
    }

    companion object {
        private lateinit var app: App

        fun get(): App {
            return app
        }
    }

    data class ConnectInfo(val device: String, val address: String, var connected: Boolean)
}